import re

from flask import Blueprint, request, jsonify, render_template
import pandas as pd
import requests
import json

from methods.bokuOs import upload_boku_img, get_bk_detail, submitFirstStep, submitSecondStep
from utils.tools import parse_number, parse_label_value, compare_labels, url_to_base64, dcc_book_detail
from utils.bokuEnum import *

bp = Blueprint("bokuOs", __name__, url_prefix="/bokuOs")


@bp.route('/test', methods=['get'])
def test():
    return "test"


# 返回自定义的登录页面
@bp.route('/loginPage', methods=['get'])
def loginPage():
    return render_template('bokuku.html')


# 登录获取session登录页面用

@bp.route('/loginApi', methods=['post'])
def loginApi():
    username = request.form.get('username')
    password = request.form.get('password')
    token = request.form.get('token')
    sessionid = request.form.get('sessionid')
    sig = request.form.get('sig')
    print(username, password, token, sessionid, sig)
    data = {
        'username': username,
        'password': password,
        'token': token,
        'sessionid': sessionid,
        'sig': sig
    }
    response = requests.post('http://gys2.bookuu.com/cloud/index.php?act=login', data=data)
    response_text = response.text
    # 解析为json格式
    response_json = json.loads(response_text)
    # 转换为utf-8编码的字符串
    utf8_text = json.dumps(response_json, ensure_ascii=False).encode('utf-8').decode('utf-8')
    print(utf8_text)
    if json.loads(utf8_text)['state'] == 0:
        return {'code': 0, 'message': json.loads(utf8_text)['message']}
    else:
        print(response.headers.get('Set-Cookie'))
        phpsessid = re.search(r'PHPSESSID=([^;]+)', response.headers.get('Set-Cookie')).group(1)
        return {'code': 200, 'message': '登录成功', 'phpsessid': phpsessid}


# 检测session是否过期
@bp.route('/checkSession', methods=['get'])
def checkSession():
    phpsessid = request.args.get('phpsessid')
    if not phpsessid:
        return "请传入phpsessid"
    response = requests.get(
        'https://gys2.bookuu.com/cloud/goods/v2/list.php?jblx=0&page=1&limit=20&op=&isbn=&spbs=&title=&zdp=&jblx=',
        cookies={
            'PHPSESSID': phpsessid,
        },
        headers={
            'X-Requested-With': 'XMLHttpRequest',
        },
        verify=False,
    )
    # 解析为json格式
    response_json = json.loads(response.text)
    if response_json.get('message', '') != '':
        return {'code': 0, 'message': response_json['message']}
    else:
        return {'code': 200, 'message': '博库登录状态未过期'}


@bp.route('/publishProduct', methods=['post'])
def publishProduct():
    data = request.get_json()
    dcc_token = data.get('dcc_token')
    serial_no = data.get('serial_no')
    session_id = data.get('session_id')
    if not dcc_token or not serial_no or not session_id:
        return {'code': 0, 'message': '请传入必填项！'}
    # 给req_type一个默认值1
    req_type = data.get('req_type', 1)  # 0 只提交基础信息；1、提交二次修改信息；2、提交基础后继续编辑提交修改信息
    # print(req_type)
    book_details_json = dcc_book_detail(serial_no, dcc_token)
    if book_details_json['code'] != 200:
        return {'code': 0, 'message': book_details_json['message']}
    if req_type == 0:
        return submitFirstStep(book_details_json, session_id)
    elif req_type == 1:
        return submitSecondStep(book_details_json, session_id)
    else:
        step1 = submitFirstStep(book_details_json, session_id)
        if step1['code'] == 0:
            return step1
        step2 = submitSecondStep(book_details_json, session_id)
        return step2
